<template>
  <div class="task-detail-container">
    <!-- 顶部导航栏 -->
    <div class="top-navbar">
      <div class="nav-left">
        <el-button 
          @click="goBack" 
          type="text" 
          class="back-btn"
          :icon="ArrowLeft"
        >
          返回
        </el-button>
        <div class="nav-title">
          <span class="title-text">{{ task?.filename || '任务详情' }}</span>
          <span class="title-subtitle">任务管理</span>
        </div>
      </div>
      <div class="nav-right">
        <el-button 
          @click="refreshTask" 
          type="text" 
          :icon="Refresh"
          class="refresh-btn"
        >
          刷新
        </el-button>
      </div>
    </div>

    <div class="main-content" v-if="task">


      <!-- 右侧主要内容 -->
      <div class="right-content">
        <!-- 任务详细信息 -->
        <el-card class="detail-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span class="card-title">任务详情</span>
              <div class="card-actions">
                <el-button 
                  @click="editTask" 
                  type="text" 
                  size="small"
                  :icon="Edit"
                >
                  编辑
                </el-button>
                <el-button 
                  @click="deleteTask" 
                  type="text" 
                  size="small"
                  :icon="Delete"
                  class="danger-btn"
                >
                  删除
                </el-button>
              </div>
            </div>
          </template>
          
          <div class="detail-grid">
            <div class="detail-item">
              <label>文件名</label>
              <span class="detail-value">{{ task.filename }}</span>
            </div>
            <div class="detail-item">
              <label>状态</label>
              <el-tag :type="getStatusType(task.status)" size="small">
                {{ getStatusText(task.status) }}
              </el-tag>
            </div>
            <div class="detail-item">
              <label>M3U8 URL</label>
              <div class="url-container">
                <el-input 
                  :value="task.url" 
                  readonly 
                  size="small"
                  class="url-input"
                >
                  <template #append>
                    <el-button 
                      @click="copyUrl" 
                      type="text" 
                      size="small"
                      :icon="CopyDocument"
                    >
                      复制
                    </el-button>
                  </template>
                </el-input>
              </div>
            </div>
            <div class="detail-item">
              <label>下载位置</label>
              <div class="path-container">
                <el-input 
                  :value="task.outputPath" 
                  readonly 
                  size="small"
                  class="path-input"
                >
                  <template #append>
                    <el-button 
                      @click="openFolder" 
                      type="text" 
                      size="small"
                      :icon="FolderOpened"
                    >
                      打开
                    </el-button>
                  </template>
                </el-input>
              </div>
            </div>
            <div class="detail-item">
              <label>并发线程数</label>
              <span class="detail-value">{{ task.concurrentThreads }}</span>
            </div>
            <div class="detail-item">
              <label>重试次数</label>
              <span class="detail-value">{{ task.retryCount }}/{{ task.maxRetries || 3 }}</span>
            </div>
            <div class="detail-item">
              <label>开始时间</label>
              <span class="detail-value">{{ formatTime(task.startTime) }}</span>
            </div>
            <div class="detail-item" v-if="task.completedTime">
              <label>完成时间</label>
              <span class="detail-value">{{ formatTime(task.completedTime) }}</span>
            </div>
            <div class="detail-item" v-if="task.outputFile">
              <label>输出文件</label>
              <div class="file-container">
                <el-input 
                  :value="task.outputFile" 
                  readonly 
                  size="small"
                  class="file-input"
                >
                  <template #append>
                    <el-button 
                      @click="openFile" 
                      type="text" 
                      size="small"
                      :icon="FolderOpened"
                    >
                      打开
                    </el-button>
                  </template>
                </el-input>
              </div>
            </div>
          </div>
        </el-card>

      
      </div>
    </div>

    <div v-else class="loading-state">
      <el-empty description="任务不存在或已删除">
        <el-button @click="goBack" type="primary">返回列表</el-button>
      </el-empty>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useTaskStore } from '../stores/taskStore'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  ArrowLeft,
  Refresh, 
  Download, 
  VideoPause, 
  VideoPlay, 
  FolderOpened,
  Delete,
  Edit,
  CopyDocument,
  CircleCheck,
  CircleClose,
  Loading,
  Tools
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const taskStore = useTaskStore()

const taskId = route.params.id
const task = computed(() => taskStore.tasks.find(t => t.id === taskId))

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    'pending': 'warning',
    'parsing': 'info',
    'downloading': 'primary',
    'merging': 'warning',
    'completed': 'success',
    'error': 'danger',
    'paused': 'info'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'pending': '等待中',
    'parsing': '解析中',
    'downloading': '下载中',
    'merging': '合并中',
    'completed': '已完成',
    'error': '失败',
    'paused': '已暂停'
  }
  return statusMap[status] || status
}

// 获取状态描述
const getStatusDescription = (status) => {
  const statusMap = {
    'pending': '任务正在等待开始',
    'parsing': '正在解析M3U8文件',
    'downloading': '正在下载视频分片',
    'merging': '正在合并视频文件',
    'completed': '任务已完成',
    'error': '任务执行失败',
    'paused': '任务已暂停'
  }
  return statusMap[status] || '未知状态'
}

// 获取状态样式类
const getStatusClass = (status) => {
  return `status-${status}`
}

// 获取进度百分比
const getProgressPercentage = () => {
  if (!task.value || !task.value.segments) return 0
  const total = task.value.segments.length
  const downloaded = task.value.downloadedSegments || 0
  return Math.round((downloaded / total) * 100)
}

// 获取进度状态
const getProgressStatus = (status) => {
  if (status === 'error') return 'exception'
  if (status === 'completed') return 'success'
  return undefined
}

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return '-'
  return new Date(timestamp).toLocaleString('zh-CN')
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (!bytes || bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 返回列表
const goBack = () => {
  router.push('/')
}

// 刷新任务
const refreshTask = () => {
  ElMessage.success('任务信息已刷新')
}

// 暂停任务
const pauseTask = async () => {
  try {
    await taskStore.pauseTask(taskId)
    ElMessage.success('任务已暂停')
  } catch (error) {
    ElMessage.error('暂停任务失败')
  }
}

// 恢复任务
const resumeTask = async () => {
  try {
    await taskStore.resumeTask(taskId)
    ElMessage.success('任务已恢复')
  } catch (error) {
    ElMessage.error('恢复任务失败')
  }
}

// 重试任务
const retryTask = async () => {
  try {
    await taskStore.retryTask(taskId)
    ElMessage.success('任务已重新开始')
  } catch (error) {
    ElMessage.error('重试任务失败: ' + error.message)
  }
}

// 编辑任务
const editTask = () => {
  ElMessage.info('编辑功能开发中...')
}

// 复制URL
const copyUrl = async () => {
  try {
    await navigator.clipboard.writeText(task.value.url)
    ElMessage.success('URL已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}

// 打开文件夹
const openFolder = () => {
  ElMessage.info('打开文件夹功能开发中...')
}

// 打开文件
const openFile = () => {
  if (task.value?.outputFile) {
    ElMessage.success('文件路径: ' + task.value.outputFile)
  }
}

// 删除任务
const deleteTask = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个任务吗？删除后无法恢复。',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await taskStore.deleteTask(taskId)
    ElMessage.success('任务已删除')
    goBack()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除任务失败: ' + error.message)
    }
  }
}

// 调试任务
const debugTask = async () => {
  try {
    const result = await window.electronAPI.debugTask(taskId)
    if (result.success) {
      ElMessage.success('调试完成，请查看控制台输出')
    } else {
      ElMessage.error('调试失败: ' + result.error)
    }
  } catch (error) {
    ElMessage.error('调试失败: ' + error.message)
  }
}

// 刷新分片信息
const refreshSegments = () => {
  ElMessage.success('分片信息已刷新')
}

// 导出分片列表
const exportSegments = () => {
  if (!task.value?.segments) {
    ElMessage.warning('暂无分片信息')
    return
  }
  
  const csvContent = [
    '序号,URL,时长(秒)',
    ...task.value.segments.map(segment => 
      `${segment.index},${segment.url},${segment.duration}`
    )
  ].join('\n')
  
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = `${task.value.filename}_segments.csv`
  link.click()
  
  ElMessage.success('分片列表已导出')
}

onMounted(() => {
  // 确保任务存储已初始化
  if (!taskStore.tasks.length) {
    taskStore.initialize()
  }
  
  // 如果任务不存在，尝试从localStorage重新加载
  if (!task.value) {
    console.log('Task not found, reloading from storage...')
    taskStore.loadTasksFromStorage()
    
    // 如果仍然找不到任务，显示错误
    if (!task.value) {
      ElMessage.error('任务不存在')
      goBack()
    }
  }
})
</script>

<style scoped>
.task-detail-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

/* 顶部导航栏 */
.top-navbar {
  background: #ffffff;
  border-bottom: 1px solid #e4e7ed;
  padding: 16px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.nav-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.back-btn {
  color: #606266;
  font-size: 14px;
  padding: 8px 12px;
  border-radius: 6px;
  transition: all 0.3s;
}

.back-btn:hover {
  background: #f5f7fa;
  color: #409eff;
}

.nav-title {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.title-text {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.title-subtitle {
  font-size: 12px;
  color: #909399;
}

.nav-right {
  display: flex;
  gap: 8px;
}

.refresh-btn {
  color: #606266;
  padding: 8px;
  border-radius: 6px;
  transition: all 0.3s;
}

.refresh-btn:hover {
  background: #f5f7fa;
  color: #409eff;
}

/* 主要内容区域 */
.main-content {
  flex: 1;
  display: flex;
  gap: 24px;
  padding: 24px;
  overflow: hidden;
}

/* 左侧边栏 */
.left-sidebar {
  width: 320px;
  display: flex;
  flex-direction: column;
  gap: 24px;
  flex-shrink: 0;
}

.status-overview {
  background: #ffffff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border: 1px solid #e4e7ed;
}

.status-header h3 {
  margin: 0 0 20px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 24px;
}

.status-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: #ffffff;
}

.status-pending {
  background: #e6a23c;
}

.status-parsing {
  background: #909399;
}

.status-downloading {
  background: #409eff;
}

.status-merging {
  background: #e6a23c;
}

.status-completed {
  background: #67c23a;
}

.status-error {
  background: #f56c6c;
}

.status-paused {
  background: #909399;
}

.status-info {
  flex: 1;
}

.status-text {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.status-desc {
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

.progress-section {
  margin-bottom: 24px;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  font-size: 14px;
  color: #606266;
}

.progress-percentage {
  font-weight: 600;
  color: #409eff;
}

.custom-progress :deep(.el-progress-bar__outer) {
  background: #f0f2f5;
  border-radius: 4px;
}

.custom-progress :deep(.el-progress-bar__inner) {
  border-radius: 4px;
}

.quick-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.action-btn {
  flex: 1;
  min-width: 80px;
}

/* 右侧内容 */
.right-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 24px;
  overflow-y: auto;
}

.detail-card,
.stats-card,
.actions-card {
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.card-actions {
  display: flex;
  gap: 8px;
}

.danger-btn {
  color: #f56c6c;
}

.danger-btn:hover {
  background: #fef0f0;
}

.detail-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.detail-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.detail-item label {
  font-size: 12px;
  color: #909399;
  font-weight: 500;
}

.detail-value {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
}

.url-container,
.path-container,
.file-container {
  width: 100%;
}

.url-input,
.path-input,
.file-input {
  width: 100%;
}

.url-input :deep(.el-input__wrapper),
.path-input :deep(.el-input__wrapper),
.file-input :deep(.el-input__wrapper) {
  background: #fafafa;
  border: 1px solid #e4e7ed;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 20px;
}

.stat-item {
  text-align: center;
  padding: 20px;
  background: #fafafa;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.stat-number {
  font-size: 24px;
  font-weight: 700;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 12px;
  color: #909399;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  flex-wrap: wrap;
}

.action-btn {
  min-width: 120px;
}

/* 加载状态 */
.loading-state {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .main-content {
    flex-direction: column;
  }
  
  .left-sidebar {
    width: 100%;
  }
  
  .detail-grid {
    grid-template-columns: 1fr;
  }
  
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .top-navbar {
    padding: 12px 16px;
  }
  
  .main-content {
    padding: 16px;
    gap: 16px;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .action-btn {
    width: 100%;
  }
}
</style> 